package cn.yusei.teamTribe.dao;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Component
public class JedisDAO implements InitializingBean{

	@Value("${redisUrl:redis://localhost:6379}")
	private String redisUrl;
	
	private JedisPool jedisPool;

	public void afterPropertiesSet() {
		jedisPool = new JedisPool(redisUrl);
	}
	
	private Jedis getConnection()
	{
		Jedis jedis = null;
		jedis = jedisPool.getResource();
		return jedis;
	}
	
	public void incr(String key){
		Jedis jedis = null;
		try{
			jedis = getConnection();
			jedis.incr(key);
		}
		finally {
			jedis.close();
		}
	}

	public Long bitcout(String key){
		Jedis jedis = null;
		Long day = null;
		try{
			jedis = getConnection();
			day = jedis.bitcount(key);
		}
		finally {
			jedis.close();
		}
		return day;
	}

	public boolean getbit(String key,long offset){
		Jedis jedis = null;
		Boolean flag = null;
		try{
			jedis = getConnection();
			flag = jedis.getbit(key,offset);
		}
		finally {
			jedis.close();
		}
		return flag;
	}


	public void setbit(String key,long offset,String value){
		Jedis jedis = null;
		try{
			jedis = getConnection();
			jedis.setbit(key,offset,value);
		}
		finally {
			jedis.close();
		}
	}
	
	public String get(String key)
	{
		Jedis jedis = null;
		String value = null;
		try
		{
			jedis = getConnection();
			value = jedis.get(key);
		}
		finally{
			jedis.close();
		}
		return value;
	}
	
	public void del(String key)
	{
		Jedis jedis = null;
		try {
			jedis = getConnection();
			jedis.del(key);
		}
		finally{
			jedis.close();
		}
	}

	public void setex(String key, int time, String value)
	{
		Jedis jedis = null;
		try {
			jedis = getConnection();
			jedis.setex(key, time, value);
		}
		finally{
			jedis.close();
		}
	}
	
	public void set(String key, String value)
	{
		Jedis jedis = null;
		try {
			jedis = getConnection();
			jedis.set(key, value);
		}
		finally{
			jedis.close();
		}
	}
}
